package com.library.exception;

import com.library.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 功能描述
 *
 * @author: LDH
 * @date: 2022年05月16日 19:23
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 用户 token 过期
     * @return
     */
    @ExceptionHandler(value = TokenAuthExpiredException.class)
    @ResponseBody
    public Result tokenExpiredExceptionHandler(){
        log.warn("用户 token 过期");
        return new Result<>().error("","token 过期",400);
    }

    /**
     * 功能描述: 参数异常捕获
     * @Param: [e]
     * @Return: com.library.common.Result
     * @Author: LDH
     * @Date: 2022/6/20 15:51
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result handleValidation(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                FieldError fieldError = (FieldError) errors.get(0);
                return new Result<>().error(e.getClass().getName(), fieldError.getDefaultMessage(),400);
            }
        }
        return new Result<>().OK("请求参数有误");
    }



    /**
     * 功能描述: 全局异常捕获
     * @Param: [e]
     * @Return: com.library.common.Result
     * @Author: LDH
     * @Date: 2022/6/20 15:23
     */
    // 捕获所有异常
    @ExceptionHandler({Exception.class})
    // 以rest方式响应给客户端
    @ResponseBody
    public Result exceptionHandler(Exception e){
        log.warn(e.getMessage());
        return new Result<>().error(e.getClass().getName(),e.getMessage(),500);
    }
}